<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-select v-model="filters.state" placeholder="请选择" clearable>
            <el-option label="离职" value="0"></el-option>
            <el-option label="在职" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="emps" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="员工姓名" width="140" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="140" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="手机" width="140"  sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="140"  sortable>
      </el-table-column>
      <el-table-column prop="departments.name" label="所属部门" width="140"  sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="140"  sortable>
        <template scope="scope">
          <div v-if="scope.row.state == 0" slot="reference" class="name-wrapper">
            <el-tag size="medium" type="danger">离职</el-tag>
          </div>
          <div v-if="scope.row.state == 1" slot="reference" class="name-wrapper">
            <el-tag size="medium" type="success">在职</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" >
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑与新增界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm" validate-on-rule-change>
        <el-form-item label="员工姓名" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <!--<el-form-item label="密码" prop="password">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>-->
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="saveForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-cascader v-model="saveForm.department_id"
                       :options="tree"
                       :props="{
                          checkStrictly:true,
                          label:'name',
                          value:'id',
                       }"
                       clearable></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>


  </section>
</template>

<script>

export default {
  data() {
    return {
      filters: {
        keyword:'',
        state:''
      },
      emps: [],
      total: 0,
      currentPage:1,
      pageSizes:[5,10,15,30],
      pageSize:10,
      page: 1,
      listLoading: false,
      sels: [],//列表选中列
      title:'',
      tree:[],//存放部门树
      employees:[],
      departments:[],
      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,
      saveFormRules: {
        username: [
          { required: true, message: '请输入姓名', trigger: 'blur' }//触发校验
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }//触发校验
        ],
        phone: [
          { required: true, message: '请输入手机', trigger: 'blur' }//触发校验
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }//触发校验
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        username:null,
        state:1,
        email:null,
        age:null,
        phone:null,
        department_id:null,

      },

      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }//触发校验
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }//触发校验
        ],
      },
      //新增界面数据
      addForm: {
        id: null,
        name: '',
        sn:'',
        state:1,
        manager:null,
        parent:null,
      }

    }
  },
  methods: {
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getemps();
    },
    handleSizeChange(val){
      this.pageSize = val;
      this.getemps()
    },
    search(){//查询
      this.currentPage = 1;
      this.getemps()
    },
    //获取部门列表
    getemps() {
      let para = {
        currentPage:this.currentPage,
        pageSize: this.pageSize,
        keyword: this.filters.keyword,
        state: this.filters.state
      };
      listLoading: true,//开启忙等
          //获取分页数据
          this.$http.post("/emp/pagelist",para).then(res => {
            this.emps = res.data.data
            this.total = res.data.total
            listLoading: false//开启忙等
          })
    },
    //获取员工列表
    getemployees(){
      this.$http.get("/emp/list").then(res =>{
        this.employees = res.data
      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.delete("/emp/"+row.id).then(res => {
          this.listLoading = false;
          if (res.data.success) {//后台返回成功
            this.$message.success(res.data.message)
          } else {//后台返回失败
            this.$message.error(res.data.message)
          }
          this.currentPage = 1;//跳转回第一页
          this.getemps()
        }).catch(res =>{
          this.$message.error(res.data.message)
        })
      }).catch(() => {//点击取消

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {

      this.title = "编辑"
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
      if(this.$refs['saveForm']){
        this.$refs['saveForm'].resetFields();//重置表单验证
      }
    },
    //显示新增界面
    handleAdd: function (row) {
      this.title = "新增"
      this.saveFormVisible = true;
      this.saveForm = {//清空表单（置空）
        id:null,
        name: '',
        sn:'',//部门编号
        state:1,//状态
        manager:null,//部门经理
        parent:null//上级部门
      };
      if(this.$refs['saveForm']){
        this.$refs['saveForm'].resetFields();//重置表单验证
      }
    },
    //编辑与新增
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.saveForm);//数据克隆
            if (para.department_id){
              if (typeof para.department_id == "object"){
                para.department_id = para.department_id[para.department_id.length-1]
              }
            }
            this.$http.put("/emp",para).then(res => {
              this.saveLoading = false;//关闭忙等
              if (res.data.success) {//后台返回成功
                this.$message.success(res.data.message)
                //重置表单验证
                this.$refs['saveForm'].resetFields();
                this.saveFormVisible = false;//关闭模态框
              } else {//后台返回失败
                this.$message.error(res.data.message)
              }
              this.getemps()
            })
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.patch("/emp",ids).then(res => {//删除成功
          this.listLoading = false;//关闭忙等
          if (res.data.success) {//后台返回成功
            this.$message.success(res.data.message)
          } else {//后台返回失败
            this.$message.error(res.data.message)
          }
          this.currentPage = 1;//跳转回第一页
          this.getemps()
        }).catch(res =>{
          this.$message.error(res.data.message)
        })
      }).catch(() => {

      });
    },
    //获取部门树
    getTree(){
      this.$http.get("/dept/getTree").then(res =>{
        this.tree = res.data
      })
    }
  },
  mounted() {
    this.getemps();
    this.getemployees();
    this.getTree();
  }
}

</script>

<style scoped>

</style>